package zz.demo.springCloud.adapter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhangz on 2018/3/18.
 */
public class RateLimiterAdapter {

    private String type;
    private int permits;
    private long timeout;
    private TimeUnit unit;
    private RateLimiter rateLimiter;

    public RateLimiterAdapter(String type, RateLimiter rateLimiter) {
        this.type = type;
        this.rateLimiter = rateLimiter;
        this.permits = 1;
        this.timeout = 0L;
        this.unit = null;
    }

    public RateLimiterAdapter(String type, RateLimiter rateLimiter, int permits, long timeout, TimeUnit unit) {
        this.type = type;
        this.rateLimiter = rateLimiter;
        this.permits = permits;
        this.timeout = timeout;
        this.unit = unit;
    }

    public boolean doLimited() {
        return this.doLimited(this.permits, this.timeout, this.unit);
    }

    public boolean doLimited(int permits, long timeout, TimeUnit unit) {
        if (RateLimiterAdapterHolder.BlockChannel.equals(type)) {
            this.rateLimiter.acquire(permits);
            // TODO
            return true;
        } else if (RateLimiterAdapterHolder.UnBlockChannel.equals(type)) {
            if (timeout == 0L) {
                return this.rateLimiter.tryAcquire(permits);
            } else {
                return this.rateLimiter.tryAcquire(permits, timeout, unit);
            }
        } else {
            // TODO
            return false;
        }
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public RateLimiter getRateLimiter() {
        return rateLimiter;
    }

    public void setRateLimiter(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    public int getPermits() {
        return permits;
    }

    public void setPermits(int permits) {
        this.permits = permits;
    }

    public long getTimeout() {
        return timeout;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    public TimeUnit getUnit() {
        return unit;
    }

    public void setUnit(TimeUnit unit) {
        this.unit = unit;
    }

    public static class RateLimiterAdapterHolder {
        //阻塞模式的转发，执行rateLimiter中的acquire方法。
        public static final String BlockChannel = "blockChannel";
        //非阻塞模式的转发，执行tryAcquire方法。
        public static final String UnBlockChannel = "unBlockChannel";
        // 默认最大限流
        public static final int Max = 1000;
    }
}
